package com.itdct.onflow.system.generator.core

import com.itdct.onflow.com.itdct.onflow.system.generator.config.SysGeneratorConfig
import com.itdct.onflow.com.itdct.onflow.system.generator.context.SysGeneratorContext
import com.itdct.onflow.com.itdct.onflow.system.generator.util.JdbcHelper
import com.itdct.onflow.core.extend.logWarn
import com.itdct.onflow.generator.core.EntityAnalyse
import com.itdct.onflow.system.api.entity.SysApiEntity
import com.itdct.onflow.system.api.entity.SysApiMenuEntity
import com.itdct.onflow.system.menu.entity.SysMenuEntity
import java.sql.Connection

/**
 * @author Zhouwx
 * @date 2025/9/8 18:23:12
 * @version 1.0
 * @description
 */
class SyncApiMenuCore {
    fun syncApiMenu(context: SysGeneratorContext, generatorConfig: SysGeneratorConfig) {
        val classModel = context.classModel
        val classNameLowCamel = classModel.classNameLowCamel
        val connection = context.connection ?: throw Exception("connection is null")

        val entityAnalyse = EntityAnalyse<SysApiMenuEntity>(generatorConfig)
        val sysApiMenuClassModel = entityAnalyse.analyseClass(SysApiMenuEntity::class.java)
        context.sysApiMenuClassModel = sysApiMenuClassModel

        if (context.pageMenuId == 0L) {
            // INFO: Zhouwx: 2025/9/8 重新加载Page信息
            syncMenu(context, connection, "Page")
        }

        if (context.addMenuId == 0L) {
            syncMenu(context, connection, "Add")
        }

        if (context.editMenuId == 0L) {
            syncMenu(context, connection, "Edit")
        }

        var contextPath = ""
        if (generatorConfig.contextPath.isNotBlank()) {
            contextPath = generatorConfig.contextPath
        }
        val apiPrefix = "${contextPath}/${classNameLowCamel}/"

        val allApiEntities = JdbcHelper.selectAll<SysApiEntity>(connection, context.sysApiClassModel)
        val apiMap = allApiEntities.associateBy { it.url }

        val sysApiMenuEntities = ArrayList<SysApiMenuEntity>()
        if (context.pageMenuId != 0L) {
            apiMap[apiPrefix + "page." + generatorConfig.apiSuffix]?.also {
                val apiId = it.id!!
                initSysApiMenuEntity(generatorConfig, apiId, context.pageMenuId, context, sysApiMenuEntities)
            }

            apiMap[apiPrefix + "delete." + generatorConfig.apiSuffix]?.also {
                val apiId = it.id!!
                initSysApiMenuEntity(generatorConfig, apiId, context.pageMenuId, context, sysApiMenuEntities)
            }
        }

        if (context.editMenuId != 0L) {
            apiMap[apiPrefix + "update." + generatorConfig.apiSuffix]?.also {
                val apiId = it.id!!
                initSysApiMenuEntity(generatorConfig, apiId, context.editMenuId, context, sysApiMenuEntities)
            }

            apiMap[apiPrefix + "detail." + generatorConfig.apiSuffix]?.also {
                val apiId = it.id!!
                initSysApiMenuEntity(generatorConfig, apiId, context.editMenuId, context, sysApiMenuEntities)
            }
        }

        if (context.addMenuId != 0L) {
            apiMap[apiPrefix + "add." + generatorConfig.apiSuffix]?.also {
                val apiId = it.id!!
                initSysApiMenuEntity(generatorConfig, apiId, context.addMenuId, context, sysApiMenuEntities)
            }
        }

        // INFO: Zhouwx: 2025/9/9 找到关联的接口，匹配后提供关联关系
        classModel.fieldList.filter {
            it.targetClass != null && it.targetClassName != null
        }.forEach {
            val targetClassName = it.targetClassName!!
            val targetClassNameLowCamel = targetClassName.substring(0, 1).lowercase() + targetClassName.substring(1)
            val targetFieldName = it.targetFieldName
            val targetFieldNameBigCamel = targetFieldName.substring(0, 1).uppercase() + targetFieldName.substring(1)
            val url = """
${contextPath}/${targetClassNameLowCamel}/select${targetFieldNameBigCamel}List.${generatorConfig.apiSuffix}
            """.trimIndent()
            apiMap[url]?.also {
                val apiId = it.id!!
                initSysApiMenuEntity(generatorConfig, apiId, context.pageMenuId, context, sysApiMenuEntities)
                initSysApiMenuEntity(generatorConfig, apiId, context.editMenuId, context, sysApiMenuEntities)
            }
        }

        if (sysApiMenuEntities.isNotEmpty()) {
            JdbcHelper.insertBatch(connection, sysApiMenuClassModel, sysApiMenuEntities)
        }
    }

    private fun initSysApiMenuEntity(
        generatorConfig: SysGeneratorConfig,
        apiId: Long,
        menuId: Long,
        context: SysGeneratorContext,
        sysApiMenuEntities: ArrayList<SysApiMenuEntity>
    ) {
        val findDuplicateList = JdbcHelper.selectList(context.connection!!, context.sysApiMenuClassModel, Pair(SysApiMenuEntity::apiId, apiId), Pair(SysApiMenuEntity::menuId, menuId))
        if (findDuplicateList.isNotEmpty()) {
            return
        }

        val sysApiMenuEntity = SysApiMenuEntity()
        sysApiMenuEntity.platformType = generatorConfig.platformType
        sysApiMenuEntity.apiId = apiId
        sysApiMenuEntity.menuId = menuId
        sysApiMenuEntities.add(sysApiMenuEntity)
    }

    fun syncMenu(context: SysGeneratorContext, connection: Connection, type: String) {
        val sysMenuClassModel = context.sysMenuClassModel
        val classModel = context.classModel
        val className = classModel.className
        // INFO: Zhouwx: 2025/9/8 重新加载Page信息
        val sysMenuEntities = JdbcHelper.selectList(connection, sysMenuClassModel, Pair(SysMenuEntity::name, className + type))
        if (sysMenuEntities.isEmpty()) {
            logWarn("未找到${className}${type}信息")
        } else {
            when (type) {
                "Page" -> {
                    context.pageMenuId = sysMenuEntities[0].id!!
                    context.pageMenuEntity = sysMenuEntities[0]
                }

                "Edit" -> {
                    context.editMenuId = sysMenuEntities[0].id!!
                    context.editMenuEntity = sysMenuEntities[0]
                }

                "Add" -> {
                    context.addMenuId = sysMenuEntities[0].id!!
                    context.addMenuEntity = sysMenuEntities[0]
                }
            }
        }
    }
}